package com.jxy.homepage.config.aop;

import com.jxy.homepage.config.annotation.ControllerWebLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * WebLogAspect
 *
 * @author Jxy
 * @date 2022/3/8
 * @Description AOP 给各个接口增加访问日志 可持久化
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect {
    static final ThreadLocal<Map<String, Object>> ctx = new ThreadLocal<>();

    /**
     * 切点 web.api包下 类
     */
    @Pointcut("execution(public * com.jxy.homepage.web.api.*.*(..))")
    public void webLog() {
    }

    @Before(value = "webLog() && @annotation(controllerWebLog)")
    public void doBefore(JoinPoint joinPoint, ControllerWebLog controllerWebLog) {
        Map<String, Object> threadInfo = new HashMap<>(10);
        ServletRequestAttributes sa = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert sa != null;
        HttpServletRequest request = sa.getRequest();
        log.info("------------------request start--------------------------");
        log.info("URL : " + request.getRequestURL());
        threadInfo.put("url", request.getRequestURL());

        log.info("HTTP_METHOD : " + request.getMethod());
        threadInfo.put("httpMethod", request.getMethod());

        log.info("USER_AGENT"+request.getHeader("User-Agent"));
        threadInfo.put("userAgent", request.getHeader("User-Agent"));

        log.info("执行方法：" + controllerWebLog.name());
        threadInfo.put("methodName", controllerWebLog.name());
        ctx.set(threadInfo);
    }

    @AfterReturning(value = "webLog()&& @annotation(controllerWebLog)", returning = "ret")
    public void doAfterReturning(ControllerWebLog controllerWebLog, Object ret) throws Throwable {
        try {
            Map<String, Object> threadInfo = ctx.get();
            if (controllerWebLog.intoDb()) {
                //插入数据库操作
                //insertResult(threadInfo);
            }
            // 处理完请求，返回内容
            log.info("RESPONSE : " + ret);
            log.info("------------------request end--------------------------");
        }finally {
            ctx.remove();
        }
    }

    @AfterThrowing(value = "webLog()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();

        ServletRequestAttributes sra = (ServletRequestAttributes) ra;

        assert sra != null;
        HttpServletRequest request = sra.getRequest();
        // 异常信息
        log.error("{}接口调用异常，异常信息{}", request.getRequestURI(), throwable);
    }
}
